<template>
    <div class="container p-0">
        <MdEditor
                toolbarsExclude="['link', 'mermaid', 'katex', 'github']"
                v-model="text"
                @onUploadImg="uploadImgs"
                @onSave="codeSave"
        >
        </MdEditor>
    </div>

</template>

<script lang="ts">
    import {defineComponent, ref} from 'vue'
    //官网：https://blog.csdn.net/weixin_44468853/article/details/123068173
    import MdEditor from 'md-editor-v3';
    import 'md-editor-v3/lib/style.css';
    import {ElMessage} from 'element-plus'
    import {uploadImg} from '@/assets/apiRequest.js'

    export default defineComponent({
        name: "RichText",
        props: {},
        components: {MdEditor},
        setup() {
            const text = ref('');

            const codeSave = (v: string): void => {
                ElMessage.info('已保存')
                localStorage.setItem('codeSave', v)
            }

            const uploadImgs = async (files, callback) => {
                const res = await files.map((file) => {
                        return new Promise(() => {
                            //必须通过form表单预览
                            const form = new FormData();
                            form.append('file', file);
                            const data = uploadImg(form)
                            //通过then获取 promise的结果
                            data.then((e) => {
                                let img = '<img src="' + e.data.url + '" style=""/>';
                                text.value = text.value + img;
                            })
                        });
                    }
                );
                callback(res.map((item: any) => item.data.url));
            }


            return {
                codeSave,
                uploadImgs,
                text,
            }
        }
    })
</script>

<style scoped>

</style>